<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\service;

use app\index\model\Article as admin;
use app\madmin\model\Commodity;
use app\madmin\model\LiveLog;
use app\madmin\model\LiveRoom;
use app\utils\LiveErrorCode;
use app\utils\TrimData;
use think\facade\Cache;

class LiveRoomService
{
    public $key;
    public $mid;
    public function __construct()
    {
        global $mid;
        $this->key="live_async_$mid";
        $this->mid=$mid;
    }

    public function list($page,$size)
    {
        $is_live_async=Cache::get($this->key);
        if(!$is_live_async){
            $this->syncRoom();
        }

        $where = [];
        $data = request()->get();

        !empty($data['name']) && $where[] = ['anchor_wechat|title|anchor_name', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['start_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['end_time', '<=', $data['end_time']];
        if (!empty($data['room_ids'])) {
            $room_ids = explode(",", $data['room_ids']);
            $where[] = ['room_id', 'in', $room_ids];
        }
        $where[] = ['is_hide', '=', 0];
        $where[] = ['is_delete', '=', 0];
        $where[] = ['mall_id', '=', $this->mid];
        $res = LiveRoom::with(["liveGoods"])->where($where)->order('status','asc')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($res as $item) {
            foreach ($item->liveGoods as $liveGood) {
                $liveGood['goods'] = Commodity::where(['id' => $liveGood->goods_id])->field(['id',
                    'merchant_id',
                    'type',
                    'name',
                    'subtitle',
                    'master',
                    'classify_id',
                    'total',
                    'sell',
                    'original_price',
                    'sell_price',
                    'min_price',
                    'max_price',
                    'sort',
                    'is_virtual',
                    'virtual_sell',
                    'is_distribution',
                    'distribution',
                    'has_sku',
                    'audit',
                    'status',
                    'create_time',
                    'update_time'])->find();
            }
        }
        return [HTTP_SUCCESS, $res];

    }
    /**同步直播间
     * @param int $id
     * @return int
     */
    public function syncRoom()
    {
        global $mid;
        //获取店铺下的所有的直播间
        $start = 0;
        $limit = 100;
        $roomList = [];
        global $user;

        $user=new \stdClass();
        $user->mall_id=$mid;
//        dd($user->mall_id);
        while (true) {
            $roomListResult = \app\utils\LiveRoom::getLiveInfo([
                'start' => $start,
                'limit' => $limit
            ]);

            $err_msg = LiveErrorCode::getError($roomListResult);
            if (!empty($err_msg)) {
                return [HTTP_NOTACCEPT, $err_msg];
            }
            if (empty($roomListResult)) {
                break;
            }

            $roomList = array_merge($roomList, $roomListResult['room_info']);
            //如果小于limit就说明没有下一页了
            if (count($roomListResult['room_info']) <= $limit) {
                break;
            }
            $start += $limit;
        }
        $roomId = [];

        foreach ((array)$roomList as $item) {
            $model = LiveRoom::where(['room_id' => $item['roomid']])->find();
            $data = [
                'mall_id' => $mid,
                'room_id' => $item['roomid'],
                //标题
                'title' => $item['name'],
                //主播昵称
                'anchor_name' => $item['anchor_name'],
                //开始时间
                'start_time' => date('Y-m-d H:i:s', $item['start_time']),
                //结束时间
                'end_time' => date('Y-m-d H:i:s', $item['end_time']),
                //状态
                'status' => $item['live_status'],
                //背景图
                'cover_img' => $item['cover_img'],
                //分享图
                'share_img' => $item['share_img'],
                'close_like' => $item['close_like'],
                'close_goods' => $item['close_goods'],
                'close_comment' => $item['close_comment'],
                'live_type' => $item['live_type'],
                'create_time' => date("Y-m-d H:i:s")
            ];
            if (empty($model)) {
                $model = LiveRoom::create($data);
            } else {
                setAttributes($model, $data);
                $model->save();
            }
            #里面还涉及商品的信息不过比较难同步
            $roomId[] = $model->id;
        }
        //把不存在的直播间修改为已删除
        if (!empty($roomId)) {
            LiveRoom::whereNotIn('id', implode(",", $roomId))->update(['is_delete' => 1]);
        }
        Cache::set($this->key,1,10*60);

        return [HTTP_SUCCESS, 'success'];
    }
}
